const cloud = require("wx-server-sdk");
cloud.init({
  env: "cloud1-6gu96tpze57c3ae6", // 自动匹配当前环境
});
const db = cloud.database();

exports.main = async (event, context) => {
  try {
    // 1. 参数校验
    if (!event.formData) {
      throw new Error("缺少formData参数");
    }

    const formData = event.formData;
    const { operation } = event; // 只保留operation参数
    const { OPENID } = cloud.getWXContext();

    // 调试日志
    console.log("接收到的数据:", formData);
    console.log("操作类型:", operation);
    console.log("用户OPENID:", OPENID);

    // 2. 查询/更新逻辑
    const queryRes = await db
      .collection("usersDataList")
      .where({ _openid: OPENID })
      .get();

    if (queryRes.data.length > 0) {
      // 更新现有记录
      const docId = queryRes.data[0]._id;
      let updateData = {};

      if (operation === "update" && formData.id) {
        // 编辑现有记录
        const records = queryRes.data[0].records || [];
        const recordIndex = records.findIndex(
          (record) => record.id === formData.id
        );

        if (recordIndex === -1) {
          throw new Error("未找到要编辑的记录");
        }

        records[recordIndex] = { ...records[recordIndex], ...formData };
        updateData = {
          records: records,
          updatedAt: db.serverDate(),
        };
      } else if (operation === "delete" && formData.id) {
        // 删除记录
        const records = queryRes.data[0].records || [];
        const recordIndex = records.findIndex(
          (record) => record.id === formData.id
        );

        if (recordIndex === -1) {
          throw new Error("未找到要删除的记录");
        }

        records.splice(recordIndex, 1);
        updateData = {
          records: records,
          updatedAt: db.serverDate(),
        };
      } else {
        // 新增记录
        updateData = {
          records: db.command.push(formData),
          updatedAt: db.serverDate(),
        };
      }

      const updateRes = await db.collection("usersDataList").doc(docId).update({
        data: updateData,
      });

      console.log("更新结果:", updateRes);
      return { code: 200, message: "更新成功", data: updateRes };
    } else {
      // 创建新记录
      const addRes = await db.collection("usersDataList").add({
        data: {
          records: [formData],
          _openid: OPENID,
          createdAt: db.serverDate(),
          updatedAt: db.serverDate(),
        },
      });
      console.log("新增结果:", addRes);
      return { code: 200, message: "创建成功", data: addRes };
    }
  } catch (err) {
    console.error("云函数错误:", err);
    return {
      code: 500,
      message: err.message,
      errCode: err.errCode,
    };
  }
};
